package app

import (
	"flag"
	"fmt"
	"mudsv/conf"
	"mudsv/core"
	"mudsv/util/env"
	"mudsv/vpub/db/dbr"
	"mudsv/zlog"
	"os"
	"os/signal"
	"syscall"
)

// Init 最先的初始化
// @return bool
func Init() bool {
	fmt.Println("InitLead")
	var err error

	//配置初始化
	//conf.InitViper()
	conf.InitJson()

	//从命令行参数获取服务器ID
	flag.IntVar(&ServerId, "id", 0, "命令行获取服务器ID")
	flag.Parse()
	fmt.Println("服务器ID：", ServerId)

	if !conf.InitExtPublic(ServerId) {
		return false
	}

	//环境
	env.Set(conf.PubConfServer.ServerMode)
	fmt.Println("env", env.Get())

	// 日志系统初始化
	zlog.LogInit(env.IsDev())

	//
	////链接Mongo
	//constants.MgoMain, err = dbm.NewMgoBase(conf.PubConfServer.MongoHost, conf.PubConfServer.MongoPort, conf.PubConfServer.MongoDatabase)
	//if err != nil {
	//	zlog.Warn(err)
	//	return false
	//}
	//constants.MgoRecord, err = dbm.NewMgoBase(conf.PubConfServer.MongoHost, conf.PubConfServer.MongoPort, conf.PubConfServer.MongoDatabase+"_rec")
	//if err != nil {
	//	zlog.Warn(err)
	//	return false
	//}
	//

	//链接Redis
	err = dbr.Init(conf.PubConfServer.RedisAddr, conf.PubConfServer.RedisPassword, conf.PubConfServer.RedisIndex)
	if err != nil {
		zlog.Warn(err)
		return false
	} else {
		zlog.Info("redis 链接成功")
	}

	PortTcp = conf.PubConfServer.ServerPort
	PortHttp = PortTcp + 1
	ServerLocked = conf.PubConfServer.Locked

	return true
}

func WaitTermSignal() {
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill, syscall.SIGTERM)
	go func() {
		<-c
		fmt.Println("收到信号TERM，退出中...")
		close(core.GetSvCore().Signal.Stop)
	}()
	<-core.GetSvCore().Signal.Stopped
}
